import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Input,
  Icon,
  Button,
  message,
  Spin,
  Modal,
  Table,
  Tooltip,
  Divider,
  Select,
} from 'antd';
import request from '@/utils/request';
import ScrollBar from '@/components/ScrollBar';
import styles from '../styles.less';
import BusiObjAdd from './BusiObjAdd';

const namespace = 'busiObjManage';

function BusiObjInfo(props) {
  const addFormEl = useRef();
  const [loading, setLoading] = useState(false);
  const [busiObjAddTitle, setBusiObjAddTitle] = useState('新增业务对象');
  const [treeTableData, setTreeTableData] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [num, setNum] = useState(20);
  const [ruleType, setRuleType] = useState(null);
  const [moreButtonShow, setMoreButtonShow] = useState(false);
  const [applyRuleTypeList, setApplyRuleTypeList] = useState([]);
  // const [scrollRef, setScrollRef] = useState(null);

  const [expandedRowKeys, setExpandedRowKeys] = useState([]);

  useEffect(() => {
    getApplyRuleTypeListSource();
    queryForm();
  }, []);

  const getApplyRuleTypeListSource = () => {
    const res = [
      {
        name: '条件对象',
        value: 0,
      },
      {
        name: '结果对象',
        value: 1,
      },
      {
        name: '条件结果都适用',
        value: 2,
      },
    ];
    setApplyRuleTypeList(res);
  };

  const onRuletTypeChange = value => {
    if (value !== undefined && value !== null) {
      queryForm({
        busiObjNbrOrName: searchValue,
        num: num + 20,
        applyRuleObj: value,
      });
    }
    setRuleType(value);
  };

  const queryForm = params => {
    setTreeTableData([]);
    setLoading(true);
    request('pmc/pms/busiObj/queryTreeNode', {
      data: {
        busiObjId: '800100001',
        num,
        ...params,
      },
    }).then(res => {
      if (res && res.success === true && res.data) {
        setLoading(false);
        setTreeTableData(res.data.children);
        setMoreButtonShow(res.data.existMore);
      } else if (res && res.errMessage) {
        message.error(res.errMessage);
      } else {
        message.error('查询失败');
      }
    });
  };

  const onSearch = value => {
    setSearchValue(value);
    queryForm({
      busiObjNbrOrName: value,
      num: 20,
      applyRuleObj: ruleType,
    });
    setNum(20);
    saveSelectBusiObj({});
  };

  const handleQueryMore = () => {
    queryForm({
      busiObjNbrOrName: searchValue,
      num: num + 20,
      applyRuleObj: ruleType,
    });
    setNum(num + 20);
    // console.log(scrollRef);
    // scrollRef.current.scrollToBottom();
    // setScrollRef(scrollRef);
  };

  // 通过dva传递
  const saveBusiObjAddVisibleFlag = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveBusiObjAddVisibleFlag`,
      payload: params,
    });
  };

  // 通过dva保存业务对象新增类型
  const saveBusiObjAddType = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveBusiObjAddType`,
      payload: params,
    });
  };

  // 通过dva传递
  const saveSelectBusiObj = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectBusiObj`,
      payload: params,
    });
  };

  const handleAdd = () => {
    setBusiObjAddTitle('新增业务对象');
    saveBusiObjAddVisibleFlag(true);
    saveBusiObjAddType('add');
  };

  const handleModify = record => {
    saveSelectBusiObj(record);
    setBusiObjAddTitle('修改业务对象');
    saveBusiObjAddVisibleFlag(true);
    saveBusiObjAddType('modify');
  };

  const handleDelete = record => {
    Modal.confirm({
      content: '确定删除选中业务对象？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request('pmc/pms/busiObj/delete', {
          method: 'GET',
          data: { busiObjId: record.busiObjId },
        }).then(res => {
          if (res && res.success === true) {
            message.success('删除成功');
            queryForm();
            saveSelectBusiObj({});
          } else if (res && res.errMessage) {
            message.error(res.errMessage);
          } else {
            message.error('删除失败');
          }
        });
      },
    });
  };

  const handleRefresh = () => {
    request('pmc/pms/RefreshCacheController/refresh', {
      method: 'POST',
      data: {
        cacheName: 'all',
      },
    }).then(res => {
      if (res && res.resultCode === '0') {
        message.success('刷新缓存成功');
        queryForm();
      } else if (res && res.resultMsg) {
        message.error(res.resultMsg);
      } else {
        message.error('刷新缓存失败');
      }
    });
  };

  const handleOk = () => {
    addFormEl.current.handleAdd().then(res => {
      if (res === true) {
        saveBusiObjAddVisibleFlag(false);
        queryForm();
      }
    });
  };

  const handleCancel = () => {
    saveBusiObjAddVisibleFlag(false);
  };

  const cellStyle = {
    maxWidth: 200,
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    textOverflow: 'ellipsis',
    cursor: 'pointer',
  };

  const columns = [
    {
      title: '业务对象名称',
      dataIndex: 'busiObjName',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => {
        return (
          <Tooltip placement="topLeft" title={text}>
            {text}
          </Tooltip>
        );
      },
    },
    {
      title: '业务对象编码',
      dataIndex: 'busiObjNbr',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => {
        return (
          <Tooltip placement="topLeft" title={text}>
            {text}
          </Tooltip>
        );
      },
    },
    {
      title: '业务对象类路径',
      dataIndex: 'className',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => {
        return (
          <Tooltip placement="topLeft" title={text}>
            {text}
          </Tooltip>
        );
      },
    },
    {
      title: '操作',
      render: (text, record) => {
        return (
          <span>
            {record.busiTypeId !== 1000 ? (
              <div>
                <a
                  onClick={() => {
                    handleModify(record);
                  }}
                >
                  编辑
                </a>
                <Divider type="vertical" />
                <a
                  onClick={() => {
                    handleDelete(record);
                  }}
                >
                  删除
                </a>
              </div>
            ) : null}
          </span>
        );
      },
    },
  ];

  // 自定义树节点图标
  const customExpandIcon = props => {
    if (
      props.record.children &&
      props.record.children != null &&
      props.record.children.length > 0
    ) {
      if (props.expanded) {
        return (
          <span style={{ marginRight: 4 }}>
            <a
              style={{ color: 'black', marginRight: 8 }}
              onClick={e => {
                props.onExpand(props.record, e);
              }}
            >
              <Icon type="minus-square" style={{ fontSize: 16 }} />
            </a>
            <Icon type="folder-open" style={{ fontSize: 16 }} />
          </span>
        );
      }
      return (
        <span style={{ marginRight: 4 }}>
          <a
            style={{ color: 'black', marginRight: 8 }}
            onClick={e => {
              props.onExpand(props.record, e);
            }}
          >
            <Icon type="plus-square" style={{ fontSize: 16 }} />
          </a>
          <Icon type="folder" style={{ fontSize: 16 }} />
        </span>
      );
    }
    return (
      <span style={{ marginRight: 4 }}>
        <Icon type="file" style={{ fontSize: 16 }} />
        &nbsp;
      </span>
    );
  };

  return (
    <ScrollBar autoHide autoHeight autoHeightMax={props.height}>
      <Spin spinning={loading}>
        <Card
          className="cute"
          title="业务对象"
          // style={{ height: props.height }}
          extra={
            <div className={styles.extra}>
              <div className="ant-input-group ant-input-group-compact">
                <Select
                  placeholder="规则对象类型选择"
                  style={{ width: '40%' }}
                  showSearch
                  allowClear
                  onChange={onRuletTypeChange}
                >
                  {applyRuleTypeList.length
                    ? applyRuleTypeList.map(item => {
                        return (
                          <Select.Option value={item.value} key={item.value}>
                            {item.name}
                          </Select.Option>
                        );
                      })
                    : null}
                </Select>
                <Input.Search
                  className={styles.Button}
                  style={{ width: '60%' }}
                  placeholder="业务对象名称、编码搜索"
                  onSearch={onSearch}
                />
              </div>
              <div>
                <Button type="primary" className="margin-right" onClick={() => handleAdd()}>
                  新增业务对象
                </Button>
                <Button type="primary" className="margin-right" onClick={() => handleRefresh()}>
                  刷新缓存
                </Button>
              </div>
            </div>
          }
        >
          <Table
            rowKey={record => record.busiObjId}
            columns={columns}
            pagination={false}
            dataSource={treeTableData}
            rowClassName={record => {
              return record.busiObjId === props.selectBusiObj.busiObjId ? styles.clickRowStyle : '';
            }}
            onRow={record => {
              return {
                onClick: () => {
                  saveSelectBusiObj(record);
                },
              };
            }}
            expandIcon={props => customExpandIcon(props)}
            // rowExpandable={true}
            // expandRowByClick={true}
            // expandedRowKeys={expandedRowKeys}
            // scrollTo={expandedRowKeys[0]}
            onExpand={(expanded, record) => {
              if (expanded) {
                expandedRowKeys.push(record.busiObjId);
                setExpandedRowKeys([...expandedRowKeys]);
              } else {
                const tempArr = expandedRowKeys.filter(item => {
                  return item !== record.busiObjId;
                });
                setExpandedRowKeys([...tempArr]);
              }
            }}
          />
          <div style={{ display: moreButtonShow ? 'block' : 'none' }}>
            <Button type="primary" ghost onClick={() => handleQueryMore()}>
              加载更多
            </Button>
          </div>
        </Card>

        {/* 新增业务对象 */}
        <Modal
          title={busiObjAddTitle}
          visible={props.busiObjAddVisibleFlag}
          onOk={handleOk}
          onCancel={handleCancel}
          width="70%"
          destroyOnClose
        >
          <BusiObjAdd cRef={addFormEl} />
        </Modal>
      </Spin>
    </ScrollBar>
  );
}
export default connect(({ busiObjManage, setting }) => ({
  busiObjAddVisibleFlag: busiObjManage.busiObjAddVisibleFlag,
  busiObjAddType: busiObjManage.busiObjAddType,
  selectBusiObj: busiObjManage.selectBusiObj,
  size: setting.size,
}))(Form.create({})(BusiObjInfo));
